package com.sto.stoapp.activity.sales;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.camera.CameraActivity;
import com.sto.stoapp.dataprocess.ProcessScanCode;
import com.sto.stoapp.db.StoDataBaseOperation;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.manager.SqlSelectTableManager;
import com.sto.stoapp.entity.CameraEntity;
import com.sto.stoapp.entity.DataBusinessEntity;
import com.sto.stoapp.entity.ProblemEntity;
import com.sto.stoapp.http.BaseMessage;
import com.sto.stoapp.listener.StoOnClickListener;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.manager.SoundManager;
import com.sto.stoapp.manager.UnSentPictureManager;
import com.sto.stoapp.status.EnumScanCode;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.util.BillFilterUtil;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.util.UnifiedStaticType;
import com.sto.stoapp.widget.StoHhmEditText;
import com.sto.stoapp.widget.StoHhmEditText.EditClickListener;
import com.sto.stoapp.widget.StoListenerActivity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SalesProblemPiecePhotoActivity extends StoListenerActivity {
	private StoHhmEditText cause;

	private DataBusinessEntity dataBusiness;
	private String busiType = HomeBroadAction.AVIATION_SCANNER_BROAD;

	private final int CAUSE_RESULT = 0xfe;
	// private List<EditText> edit = new ArrayList<EditText>();
	private String CauseCode = "";
	private String CauseName = "";

	private final int CAMERA_RESULT = 0xf;

	private Button photograph, savePicture;

	private ImageView scanImage;

	private Bitmap mBitmap;

	private PopupWindow popupWindow;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sto_problem_piece_photo);
		Bundle extras = getIntent().getExtras();
		busiType = extras.getString("busiType");
		this.setTitleBottom(R.string.problem_piece, busiType);
		initPointLayout(true);
		initWidget();
		initListen();
		initScanListener();
		dataBusiness = new DataBusinessEntity();
		dataBusiness.initInsertData();
		/*
		 * 添加航空扫描员-问题件
		 * 
		 * @修改人：mgf
		 */
		// 航空-扫描-留仓件
		if (busiType.equals(HomeBroadAction.AVIATION_SCANNER_BROAD)) {
			initScanRecordAdapter(EnumTableNames.STATUS_TABLE_AVIATION_PROBLEM);
		} else {
			initScanRecordAdapter(EnumTableNames.STATUS_TABLE_PROBLEM);
		}

	}

	private void initWidget() {
		code = (StoHhmEditText) this
				.findViewById(R.id.problem_odd_numbers_text);
		cause = (StoHhmEditText) this.findViewById(R.id.cause_text);

		scanImage = (ImageView) findViewById(R.id.scan_image);
		photograph = (Button) findViewById(R.id.photograph);
		savePicture = (Button) findViewById(R.id.save_picture);
		if (busiType.equals(HomeBroadAction.AVIATION_SCANNER_BROAD)) {
			addUploadTable(EnumTableNames.STATUS_TABLE_AVIATION_PROBLEM);
		} else {
			addUploadTable(EnumTableNames.STATUS_TABLE_PROBLEM);
		}
		// edit.add(code);
	}

	/**
	 * 监听控件
	 */
	private void initListen() {
		cause.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				onBackPressed();
			}

			@Override
			public void onEditClickListener(View v) {
//				SelectCause();
			}
		});

		findViewById(R.id.btn_select).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				SelectCause();
			}
		});

		code.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				cause.requestFocus();
			}

			@Override
			public void onEditClickListener(View v) {
				if (code.getText().toString().length() == 0) {
					Helper.showSoundToast(SalesProblemPiecePhotoActivity.this,
							getString(R.string.code_empty), false);
				} else {
					onScanResults(code.getText().toString());
				}
			}
		});

		photograph.setOnClickListener(new StoOnClickListener(this) {

			@Override
			public void mHonClick(View view) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(SalesProblemPiecePhotoActivity.this,
						CameraActivity.class);
				startActivityForResult(intent, CAMERA_RESULT);
			}
		});

		scanImage.setOnClickListener(new StoOnClickListener(this) {

			@Override
			public void mHonClick(View view) {
				initPopWindow();
			}
		});

		savePicture.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (CheckScanCode(code.getText().toString())) {
					processScanData();
				}
			}
		});

		/*
		 * code.setEditScanListener(new EditScanListener() {
		 * 
		 * @Override public void onScan() { ScanOpen(); }
		 * 
		 * @Override public void offScan() { ScanOff(); } });
		 */

		/*
		 * code.setOnClickListener(new StoOnClickListener(this) {
		 * 
		 * @Override public void mHonClick(View v) {
		 * onScanResults(code.getText().toString()); } });
		 */
	}

	/**
	 * 选择原因
	 */
	private void SelectCause() {
		String user_widget = "";
		if (UnifiedStaticType.loginType.equals(BaseMessage.SALES_VERSION)
				|| UnifiedStaticType.loginType
						.equals(BaseMessage.SCANNER_VERSION)) {
			user_widget = "N";
		}
		if (UnifiedStaticType.loginType.equals(BaseMessage.CENTER_VERSION)
				|| UnifiedStaticType.loginType
						.equals(BaseMessage.AVIATION_A_VERSION)
				|| UnifiedStaticType.loginType
						.equals(BaseMessage.AVIATION_Y_VERSION)) {
			user_widget = "C";
		}
		try {
			ProblemEntity tableParcel = new ProblemEntity();
			if (cause.getText().length() == 0) {
				tableParcel
						.setSelectSql(SqlSelectTableManager.SQL_CAUSE_INFO_ALL);
				tableParcel.setSelectField(new String[] { user_widget });
			} else {
				tableParcel
						.setSelectSql(SqlSelectTableManager.SQL_CAUSE_INFO_ONLY);
				tableParcel.setSelectField(new String[] {
						cause.getText().toString(), user_widget });
			}
			Intent intent = new Intent(SalesProblemPiecePhotoActivity.this,
					StoProblemSelectActivity.class);
			intent.putExtra("tableData", tableParcel);

			startActivityForResult(intent, CAUSE_RESULT);
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("SelectCause", e.getMessage());
		}
	}

	/**
	 * 扫描码判断
	 * 
	 * @param code
	 *            扫描码
	 * @return true/ok or false
	 */
	private boolean CheckScanCode(String code) {
		boolean ret = false;

		EnumScanCode status = ProcessScanCode.getInstance(this)
				.ScanCodeResolve(code, EnumTableNames.STATUS_TABLE_PROBLEM);

		switch (status) {
		// 条码空
		case CODE_EMPTY:
			Helper.showSoundToast(SalesProblemPiecePhotoActivity.this,
					getString(R.string.code_empty), false);
			break;

		// 非法条码
		case CODE_ILLEGAL:
			Helper.showSoundToast(this, getString(R.string.error_code), false);
			break;
		// 成功条码
		case CODE_WAY_BILL:

			ret = true;
			break;
		default:
			break;
		}

		return ret;
	}

	/**
	 * 扫描数据处理
	 */
	@SuppressLint("NewApi")
	private void processScanData() {
		try {
			if (mBitmap == null) {
				Helper.showSoundToast(this,
						getString(R.string.please_pictures), false);
				return;
			}
			if (!code.getText().toString().isEmpty() && !CauseCode.equals("")
					&& CauseName.equals(cause.getText().toString())) {

				//Add by wj过滤单号
				boolean isFilter= BillFilterUtil.isFilter(code.getText().toString().trim(),this);
				if(isFilter){
					showFilterDialog(code.getText().toString().trim());
					return;
				}
				//End by wj

				if (addPieceRecord()) {
					UnSentPictureManager.getInstance(this).addPictureCount();
					this.addCodeNumber();

					setSaveData(true);

					Helper.showSoundAndVibrator(this, true);
					// SoundManager.getInstance(this).playSuccessSound();
					addScanRecordInfo(code.getText().toString());
					// ticketNumber.setText(String.valueOf(++count));
					code.setSelection(code.length());

					// 保存图片
					if (mBitmap != null) {
						saveFile(mBitmap);
						mBitmap = null;
						code.setText("");
						code.requestFocus();
						scanImage.setImageResource(R.drawable.default_img);
					}
				}
				// 提示插入数据失败
				else {
					Helper.showSoundToast(this,
							getString(R.string.code_repeat), false);
				}

				ScanOpen();
			} else if (code.getText().toString().isEmpty()) {
				// 提示单号不能为空

			} else if (cause.getText().toString().isEmpty()) {
				// 原因不能为空
				SoundManager.getInstance(this).playFailureSound();
				Helper.showToast(this, "原因不能为空");
				cause.requestFocus();
				cause.setText("");
			} else if (CauseCode.equals("")
					|| !CauseName.equals(cause.getText().toString())) {
				// 没有选择问题件原因
				SoundManager.getInstance(this).playFailureSound();
				Helper.showToast(this, "请选择正确的问题件原因!");
				cause.requestFocus();
			}
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("processScanData", e.getMessage());
		}
	}

	/**
	 * 数据保存
	 * 
	 * @return true/成功 or false/失败
	 */
	private boolean addPieceRecord() {
		boolean ret;

		dataBusiness.setBar_code_number(code.getText().toString());
		dataBusiness.setCodeType(getExpType(code.getText().toString()));
		// 原因
		dataBusiness.setReason_number(CauseCode);
		dataBusiness.setUser_defined5(cause.getText().toString());
		// 网点编号
		dataBusiness.setNet_code(StoFilePreference.getInstance(this)
				.getSiteCode());
		// 网点名称
		dataBusiness.setSend_person(StoFilePreference.getInstance(this)
				.getSiteName());
		// 工号
		dataBusiness.setJob_number(StoFilePreference.getInstance(this)
				.getUserCode());
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat(
				UnifiedStaticType.SIMPLE_DATE_FORMAT);
		String nowDate = format.format(date);
		dataBusiness.setUser_defined3(nowDate);
		// // 航空-扫描-问题件
		if (busiType.equals(HomeBroadAction.AVIATION_SCANNER_BROAD)) {
			dataBusiness
					.setCommand_type(EnumTableNames.STATUS_TABLE_AVIATION_PROBLEM
							.getOpCode());
			ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
					EnumTableNames.STATUS_TABLE_AVIATION_PROBLEM);
		} else {
			dataBusiness.setCommand_type(EnumTableNames.STATUS_TABLE_PROBLEM
					.getOpCode());
			ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
					EnumTableNames.STATUS_TABLE_PROBLEM);
		}

		return ret;
	}

	/**
	 * 选择列表返回的结果
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CAUSE_RESULT && resultCode == RESULT_OK) {
			String Cause = data.getStringExtra("Name");
			CauseCode = data.getStringExtra("CauseCode");
			if (Cause != null) {
				cause.setText(Cause);
				CauseName = Cause;
				cause.setSelection(cause.length());
				code.requestFocus();
			}
		} else if (requestCode == CAUSE_RESULT
				&& resultCode == RESULT_FIRST_USER) {
			CauseCode = "";
			CauseName = "";
			cause.setText("");
			Helper.showSoundToast(this, getString(R.string.undefined), false);
		} else if (requestCode == CAMERA_RESULT
				&& resultCode == Activity.RESULT_OK) {
			CameraEntity entity = data.getParcelableExtra("bitmapPicture");
			if (entity != null) {
				mBitmap = entity.getDraw();
				scanImage.setImageBitmap(mBitmap);
				savePicture.requestFocus();
			}
			// ScanOpen();
		} else {

		}

	}

	/**
	 * 放大图片显示
	 */
	@SuppressWarnings("deprecation")
	private void initPopWindow() {
		if (mBitmap == null) {
			return;
		}
		Display display = getWindowManager().getDefaultDisplay();
		// 加载popupWindow的布局文件
		View contentView = LayoutInflater.from(this).inflate(
				R.layout.sto_picture_popup, null);
		// 设置popupWindow的背景颜色
		contentView.setBackgroundColor(Color.BLACK);
		// 声明一个弹出框
		popupWindow = new PopupWindow(contentView, LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT);
		popupWindow.setFocusable(true);
		popupWindow.setOutsideTouchable(true);
		popupWindow.showAtLocation(code, Gravity.CENTER_VERTICAL, 0, 0);
		final ImageView imageView = (ImageView) contentView
				.findViewById(R.id.dis_picture);
		int width = display.getWidth() - 50;
		int height = display.getHeight() - 50;
		// 将图片设置为宽，高，在这儿就可以实现图片的大小缩放
		Bitmap resize = Bitmap.createScaledBitmap(mBitmap, width, height, true);
		// Matrix m = new Matrix();
		// m.setRotate(90); // 逆时针旋转15度
		// // 做好旋转与大小之后，重新创建位图，0-width宽度上显示的区域，高度类似
		// Bitmap b = Bitmap.createBitmap(resize, 0, 0, height, width, m, true);
		// 显示图片
		imageView.setImageBitmap(resize);
		imageView.setFocusableInTouchMode(true);
		imageView.requestFocus();

		imageView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				closePopupWindow();
			}
		});

		imageView.setOnKeyListener(new OnKeyListener() {

			@SuppressWarnings("static-access")
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == event.KEYCODE_BACK) {
					closePopupWindow();
				}
				return false;
			}
		});

	}

	/**
	 * 保存文件
	 * 
	 * @param bm
	 * @throws IOException
	 */
	@SuppressLint({ "SimpleDateFormat", "NewApi" })
	private boolean saveFile(Bitmap bm) throws IOException {
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat(
				UnifiedStaticType.SIMPLE_DATE_FORMAT);
		String nowDate = format.format(date);
		String simpleDate = nowDate.replace("-", "");
		String dirPath = Environment.getExternalStorageDirectory().toString()
				+ UnifiedStaticType.WTJ_IMAGE_PATH + simpleDate + "/";

		File dirFile = new File(dirPath);// 新建目录
		if (!dirFile.exists()) {// 判断文件夹目录是否存在
			dirFile.mkdirs();// 如果不存在则创建
		}
		// String filename = code.getText().toString() + "-" + simpleDate +
		// ".jpg";
		String filename = code.getText().toString() + ".jpg";
		String filePath = dirPath + filename;

		BufferedOutputStream fOut = new BufferedOutputStream(
				new FileOutputStream(filePath));

		// OutputStream fOut = new FileOutputStream(filePath);
		bm.compress(Bitmap.CompressFormat.JPEG, 80, fOut);
		fOut.flush();
		fOut.close();
		// 保存图片路径
		if (busiType.equals(HomeBroadAction.AVIATION_SCANNER_BROAD)) {
			StoDataBaseOperation
					.getInstance(this)
					.updatePicturePath(
							EnumTableNames.STATUS_TABLE_AVIATION_PROBLEM
									.getTableName(),
							filePath,
							code.getText().toString(),
							EnumTableNames.STATUS_TABLE_AVIATION_PROBLEM
									.getOpCode());

		} else {
			StoDataBaseOperation.getInstance(this).updatePicturePath(
					EnumTableNames.STATUS_TABLE_PROBLEM.getTableName(),
					filePath, code.getText().toString(),
					EnumTableNames.STATUS_TABLE_PROBLEM.getOpCode());
		}

		return true;
	}

	private void closePopupWindow() {
		if (popupWindow != null) {
			popupWindow.dismiss();
			popupWindow = null;
		}
	}

	@Override
	public void onBackPressed() {
		// 确定退出吗?
		showNotice();
	}

	@Override
	protected void handlerScanData(String scanData) {

		if (scanData != null && !scanData.equals("")) {
			String result = scanData;
			code.setText("");
			code.setText(result);
			code.setSelection(code.length());
			photograph.requestFocus();
			if (CheckScanCode(result)) {
				Helper.showSoundAndVibrator(
						SalesProblemPiecePhotoActivity.this, true);
			}
			// if (CheckScanCode(result)) {
			// processScanData();
			// }
			// code.setText("");
		}

	}
}
